package com.mysiteforme.admin.service.impl.courseimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.mysiteforme.admin.dao.course.ChLorePointDao;
import com.mysiteforme.admin.entity.course.ChLorePoint;
import com.mysiteforme.admin.service.course.ChLorePointService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yj
 * @since 2019-04-15
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ChLorePointServiceImpl extends ServiceImpl<ChLorePointDao, ChLorePoint> implements ChLorePointService {

    @Resource
    private ChLorePointDao chLorePointDao;

    @Value("${qiniu.domain}")
    private String domain;

    @Override
    public boolean insertLorePoint(ChLorePoint chLorePoint) {
//        String videoInfo = getVideoTime(chLorePoint.getVideoUrl());
//       if (videoInfo!=null){
//           JSONObject obj = JSON.parseObject(videoInfo);
//           String videoTime = ((JSONObject)obj.get("format")).getString("duration");
//           if(videoTime!=null&&videoTime!=""){
//               chLorePoint.setVideoTimeLong(Long.parseLong(videoTime));
//           }
//       }
        return chLorePointDao.insertLorePoint(chLorePoint)>0?true:false;
    }

    @Override
    public boolean updateLorePointById(ChLorePoint chLorePoint) {
        return chLorePointDao.updateLorePointById(chLorePoint)>0?true:false;
    }

    @Override
    public boolean deleteLorePointById(String id) {

        return chLorePointDao.deleteLorePointById(id)>0?true:false;
    }

    @Override
    public String getVideoUrl(String id) {
        return chLorePointDao.getVideoUrl(id);
    }

    /**
     * 获取视频时长
     * @return
     */
    public String getVideoTime(String videoUrl){
        // 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();

        // 参数
        StringBuffer params = new StringBuffer();
        try {
            // 字符数据最好encoding以下;这样一来，某些特殊字符才能传过去(如:某人的名字就是“&”,不encoding的话,传不过去)
            params.append("name=" + URLEncoder.encode("&", "utf-8"));
            params.append("&");
            params.append("age=24");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        // 创建Get请求
        HttpGet httpGet = new HttpGet(domain+videoUrl+"?avinfo");
        // 响应模型
        CloseableHttpResponse response = null;
        try {
            // 配置信息
            RequestConfig requestConfig = RequestConfig.custom()
                    // 设置连接超时时间(单位毫秒)
                    .setConnectTimeout(5000)
                    // 设置请求超时时间(单位毫秒)
                    .setConnectionRequestTimeout(5000)
                    // socket读写超时时间(单位毫秒)
                    .setSocketTimeout(5000)
                    // 设置是否允许重定向(默认为true)
                    .setRedirectsEnabled(true).build();

            // 将上面的配置信息 运用到这个Get请求里
            httpGet.setConfig(requestConfig);

            // 由客户端执行(发送)Get请求
            response = httpClient.execute(httpGet);

            // 从响应模型中获取响应实体
            HttpEntity responseEntity = response.getEntity();
            System.out.println("响应状态为:" + response.getStatusLine());
            if (responseEntity != null) {
//                System.out.println("响应内容长度为:" + responseEntity.getContentLength());
//                System.out.println("响应内容为:" + EntityUtils.toString(responseEntity));

                return EntityUtils.toString(responseEntity);
            }else return null;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
